<?php


namespace App\Services;


use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class RollsService
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }


    public function getRolls(Request $request)
    {
        $user_id = session('admin.id');
        $user_type = session('admin.user_type');
        /*$rollNumberArr = $this->getRollsNumber($user_id, $user_type);
        if (empty($rollNumberArr)) {
            return [];
        }*/

        $userIds = $this->userService->getDistributions(4, $user_id);
        if (!empty($userIds)) {
            $userIds = array_merge($userIds, $this->userService->getDealers($userIds));
        }

        if (empty($userIds)) {
            return [];
        }

        $model = DB::table('roll_master as rm')
            ->leftJoin('roll_restlen as rr', 'rr.roll_number', 'rm.roll_number')
            ->whereNull('rr.deleted_at')
            ->whereNull('rm.deleted_at')
            ->whereIn('rr.user_id', $userIds);
        $model = filterByDateRange($model, 'rm.created_at');

        $product_type_id = (int) $request->input('product_type_id');
        $film_type_id = (int) $request->input('film_type_id');
        if (!empty($film_type_id)) {
            $model = $model->where('rm.film_type_id', $film_type_id);
        } else if (!empty($product_type_id)) {
            $model = $model->leftJoin('film_type_master as ftmm', 'rm.film_type_id', 'ftmm.id')
                ->where('ftmm.product_type_id', $product_type_id);
        }

        $status = $request->input('status');
        if ($status !== null) {
            $model = $model->where('rm.status', $status);
        }

        $distributor_id = (int) $request->input('distributor_id');
        $dealer_id = (int) $request->input('dealer_id');
        if (!empty($dealer_id)) {
            $model = $model->leftJoin('warranty_to_vehicle_coverage as wvc', 'rm.roll_number', 'wvc.roll_number')
                ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
                ->leftJoin('precut_to_vehicle_coverage as pvc', 'rm.roll_number', 'pvc.roll_number')
                ->leftJoin('precut as p', 'p.id', 'pvc.precut_kit_sale_id')
                ->where(function ($query) use ($dealer_id) {
                    $query->where(function ($q2) use ($dealer_id) {
                        $q2->where('rr.user_id', $dealer_id)
                            ->where('rr.restlen', '>', 0);
                    })
                        ->orWhere(function ($query) use ($dealer_id) {
                            $query->where('w.user_id', $dealer_id)
                                ->where('w.approved', 1)
                                ->whereNotNull('wvc.warranty_id')
                                ->whereNull('w.deleted_at')
                                ->whereNull('wvc.deleted_at');
                        })
                        ->orWhere(function ($query) use ($dealer_id) {
                            $query->where('p.created_by', $dealer_id)
                                ->whereNotNull('p.id')
                                ->whereNull('p.deleted_at')
                                ->whereNull('pvc.deleted_at');
                        });
                });

            /*$model = $model->leftJoin('roll_restlen as rd', 'rd.roll_number', 'rr.roll_number')
                ->where('rd.user_id', $dealer_id);*/
        } else if (!empty($distributor_id)) {
            $model = $model->leftJoin('warranty_to_vehicle_coverage as wvc', 'rm.roll_number', 'wvc.roll_number')
                ->leftJoin('warranty as w', 'w.id', 'wvc.warranty_id')
                ->leftJoin('precut_to_vehicle_coverage as pvc', 'rm.roll_number', 'pvc.roll_number')
                ->leftJoin('precut as p', 'p.id', 'pvc.precut_kit_sale_id')
                ->where(function ($query) use ($distributor_id) {
                    $query->where(function ($q2) use ($distributor_id) {
                        $q2->whereIn('rr.user_id', function ($query) use ($distributor_id) {
                            $query->select('id')
                                ->from('users')
                                ->where('id', $distributor_id)
                                ->orWhere('creator_id', $distributor_id);
                        })
                            ->where('rr.restlen', '>', 0);
                    })
                        ->orWhere(function ($query) use ($distributor_id) {
                            $query->whereIn('w.user_id', function ($query) use ($distributor_id) {
                                $query->select('id')
                                    ->from('users')
                                    ->where('id', $distributor_id)
                                    ->orWhere('creator_id', $distributor_id);
                            })
                                ->whereNotNull('wvc.warranty_id')
                                ->whereNull('w.deleted_at')
                                ->whereNull('wvc.deleted_at');
                        })

                        ->orWhere(function ($query) use ($distributor_id) {
                            $query->whereIn('p.created_by', function ($query) use ($distributor_id) {
                                $query->select('id')
                                    ->from('users')
                                    ->where('id', $distributor_id)
                                    ->orWhere('creator_id', $distributor_id);
                            })
                                ->whereNotNull('p.id')
                                ->whereNull('p.deleted_at')
                                ->whereNull('pvc.deleted_at');
                        });
                });
            /*$model = $model->->where('rr.user_id', $distributor_id);*/
        }

        // $select = ['rm.*', 'roll_sales.roll_id as roll_sales_id'];
        $select = ['rm.*', 'rr.restlen'];
        $model = $model->select($select)
            ->groupBy('rm.id');
        $model = $this->filterRolls($request, $model);
        $data = $model->orderByDesc('rm.id')->paginate(50);
        return $data;
    }

    protected function filterRolls(Request $request, $model)
    {
        $value = $request->input('value');
        if (empty($value)) {
            return $model;
        }
        $film = DB::table('film_type_master as ft');
        $film = filterByColumns($film, ['ft.english_value', 'ft.traditional_chiness_value', 'ft.simplified_chiness_value']);
        $film_ids = $film->get('ft.id');
        $model = $model->where(function ($query) use ($value, $film_ids) {
            $query->orWhereIn('rm.film_type_id', Arr::pluck($film_ids, 'id'))
                ->orWhere('rm.roll_number', 'like', '%'.$value.'%');
        });
        return $model;
    }

    public function getRollsNumber(int $userId, int $userType)
    {
        $userIdArr = (new UserService())->getDistributions($userType, $userId);
        if (empty($userIdArr)) {
            return [];
        }

        $data = DB::table('roll_restlen')->whereIn('user_id', $userIdArr)->select('roll_number')->groupBy('roll_number')->get();
        if (empty($data)) {
            return [];
        }

        $rollNumberArr = [];
        foreach ($data as $item) {
            $rollNumberArr[] = $item->roll_number;
        }

        return $rollNumberArr;
    }

    /**
     * 获取管理员对应的膜卷数
     *
     * @param Request $request
     * @return mixed
     */
    public function getAdminRolls(Request $request)
    {
        $model = DB::table('roll_master as rm')
            ->leftJoin('roll_restlen as rr', 'rr.roll_number', 'rm.roll_number')
            ->leftJoin('roll_sales as rs', 'rm.id', 'rs.roll_id')
            ->whereNull('rr.deleted_at')
            ->whereNull('rm.deleted_at')
            ->where('rr.user_id', 1);
        $model = filterByDateRange($model, 'rs.created_at');

        $product_type_id = (int) $request->input('product_type_id');
        $film_type_id = (int) $request->input('film_type_id');
        if (!empty($film_type_id)) {
            $model = $model->where('rm.film_type_id', $film_type_id);
        }
        if (!empty($product_type_id)) {
            $model = $model->leftJoin('film_type_master as ftmm', 'rm.film_type_id', 'ftmm.id')
                ->where('ftmm.product_type_id', $product_type_id);
        }

        $status = $request->input('status');
        if ($status !== null) {
            $model = $model->where('rm.status', $status);
        }

        $distributor_id = (int) $request->input('distributor_id');
        $dealer_id = (int) $request->input('dealer_id');
        if (!empty($distributor_id)) {
            $user_id = $distributor_id;
        }
        if (!empty($dealer_id)) {
            $user_id = $dealer_id;
        }

        if (!empty($user_id)) {
            $model = $model->where('rs.sold_to_user_id', $user_id);
            /*$model = $model->whereIn('rm.roll_number', function ($query) use ($user_id) {
                $query->select('roll_number')
                    ->from('roll_restlen')
                    ->where('user_id', $user_id);
            });*/
        }

        $select = ['rm.*', 'rr.restlen', 'rs.created_at as rs_create_at'];
        $model = $model->select($select);
        if (!empty($user_id)) {
            $model = $model->groupBy('rs.roll_id');
        } else {
            $model = $model->groupBy('rm.id');
        }
        $model = $this->filterRolls($request, $model);
        $data = $model->orderByDesc('rs_create_at')->paginate(50);
        if (!empty($data) && $data->isNotEmpty() && empty($user_id)) {
            $idArr = [];
            foreach ($data as $item) {
                $idArr[] = $item->id;
            }
            if (!empty($idArr)) {
                $sql = 'SELECT MAX(created_at) AS created_at, roll_id FROM roll_sales WHERE roll_id IN(' . implode(',', $idArr) . ') AND deleted_at IS NULL GROUP BY roll_id';
                $result = DB::select($sql);
                if (!empty($result)) {
                    foreach ($data as &$value) {
                        foreach ($result as $item) {
                            if ($item->roll_id == $value->id) {
                                $value->rs_create_at = $item->created_at;
                            }
                        }
                    }
                }
            }
        }

        return $data;
    }
}